<?php

namespace Welcomescreen\Agavi\Routing;

class CommandLineInputCallback extends \AgaviRoutingCallback {
	public function onMatched(array &$parameters, \AgaviExecutionContainer $container) {
		$stdOut = fopen('php://stdout', 'a');
		$stdIn = fopen('php://stdin', 'r');
		
		
		$parameterDefinitions = $this->getParameter('parameters', array());
		foreach($parameterDefinitions as $parameterDefinition) {
			$parameterName = $parameterDefinition['name'];
			if(isset($parameters[$parameterName])) {
				continue;
			}
			
			fwrite($stdOut, $parameterDefinition['text']);
			switch(isset($parameterDefinition['type']) ? $parameterDefinition['type'] : 'text') {
				case 'text': {
					$input = rtrim(fgets($stdIn, 1024));
				} break;
				case 'password': {
					$this->enableConsoleEcho(false);
					$input = rtrim(fgets($stdIn, 1024));
					fwrite($stdOut, PHP_EOL);
					$this->enableConsoleEcho(true);
				} break;
			}
			$parameters[$parameterName] = $input;
		}
		
		return true;
	}
	
	public function enableConsoleEcho($enable) {
		shell_exec(sprintf('/bin/stty %secho', $enable ? '' : '-'));
	}
}


?>